# --**coding:utf-8**--
# Create by author: hemq

from django.shortcuts import render
from channel.models import ChannelListConfig, Nodeconfig, Androidnodestatus, HistoryChannelapk
import filetooll, apidocBaseInfo
from channel.models import PortInfo, PortParamete
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json


# Create your views here.
def retUploadfile(request):
    '''
    return：上传文件页面
    '''
    return render(request, 'apidoc/uploadfile.html')


def getfile(request):
    '''
    接收上传文件
    '''
    if request.method == 'POST':
        # 获取版本号
        portNAme = request.POST['portName']
        portSystem = request.POST['portSystem']
        portPath = request.POST['portPath']
        filetooll.handle_upload_file(request.FILES['file'], str(request.FILES['file']), portSystem)
        apkName = str(request.FILES['file'])
        # all path 各系统路径,存储全路径
        allApiPath = apidocBaseInfo.baseSystemPath + portSystem
        AllPath = filetooll.build_portSystem_dic(allApiPath, portNAme)
        # 上传接口数据至db
        portInfo = PortInfo(portname=portNAme, portsystem=portSystem, portpath=AllPath).save()

        return render(request, 'apidoc/uploadFileSuccess.html')
    else:
        return HttpResponse('upload fail')


def dealFile(request):
    # return json info
    with open('./fileapi/help.json', 'r+') as jsoninfo:
        content = jsoninfo.read()
        return render(request, 'apidoc/test.html', {'info': content})
    pass


def index(request):
    friendui = 'woshiui'
    return render(request, 'apidoc/index.html', {'friendui': friendui})


def testTree(request):
    return render(request, 'apidoc/testt.html')


def addPort(request):
    # 上传新接口
    if request.method == 'POST':
        portNAme = request.POST['portName']
        portSystem = request.POST['portSystem']
        portPath = request.POST['portPath']
        print portNAme, portPath, portSystem

        print request.session
    else:
        return HttpResponse('请求方式错误，请使用post')

    return render(request, 'apidoc/addPort.html')


# 处理ajax 请求
@csrf_exempt
def treeview(request):
    data = request.POST
    tree = data.get('treev')

    print tree
    dd = {}
    dd['filename'] = 'getUserRelation'
    return JsonResponse(dd)


@csrf_exempt
def nodeName(request):
    payui = []
    tradeui = []
    fieldName = []  # port field name
    fieldType = []  # port field type
    fieldisMuster = []  # port fieldismuster
    fieldExplain = []  # port fieldExplain

    data = request.POST
    # 获取 客户端传入的接口文档文件名
    filename = data.get('filename')
    loginPort = PortParamete.objects.filter(portname='login')
    for logininfo in loginPort:
        fieldName.append(logininfo.fieldname)
        fieldType.append(logininfo.fieldtype)
        fieldExplain.append(logininfo.fieldexplain)
        fieldisMuster.append(logininfo.fieldismuster)

    # db fittler portname
    portname = PortInfo.objects.filter(portname=filename)

    if portname:
        # get file path
        portpath = ''
        for path in portname:
            portpath = path.portpath
        # get filecontent from portpath
        # test 写死文件路径
        filepath = './apidoc/fileapi/payui/testjson.json'
        content = filetooll.returnFileContent(filepath)
        dd = {}
        dd['tradeui'] = content
        dd['payui'] = payui
        dd['fieldName'] = fieldName
        dd['fieldType'] = fieldType
        dd['fieldisMuster'] = fieldisMuster
        dd['fieldExplain'] = fieldExplain
        return JsonResponse(dd)


@csrf_exempt
def pinInfo(request):
    '''
    treeview本身是个特殊的类型[{'text':'sss'},{'text':'bbb'}]
    数组嵌套字典，且所有元素的字典的key值均为text。
    '''
    # 存储所有接口名
    payuiName = []
    each_dic = []
    bb = {}
    # 拼接[{text:'xx'}]模式的是treeview
    all_dic = []
    payuiinfo = PortInfo.objects.filter(portsystem='phptradeui')
    for i in payuiinfo:
        # print i.portname
        payuiName.append(i.portname)
        each_dic.append(i.portname)
    for i in range(len(payuiName)):
        each_dic[i] = {'text': ''}
        all_dic.append(each_dic[i])
    for num_time in range(len(payuiName)):
        all_dic[num_time]['text'] = payuiName[num_time]
    # 若增加系统，则内部添加nodes节点即可
    treeviewInfo = {
        'text': "jdb",  # 节点显示的文本值  string
        'selectable': 'true',  # 标记节点是否可以选择。false表示节点应该作为扩展标题，不会触发选择事件。  string
        'state': {  # 描述节点的初始状态    Object
            'checked': 'true',  # 是否选中节点
        },
        'tags': ['标签信息1', '标签信息2'],  # //向节点的右侧添加附加信息（类似与boostrap的徽章）    Array of Strings
        'nodes': [{
            'text': "Child 1",

            'nodes': all_dic
        }, {
            'text': "Child 2",
            'nodes': all_dic
        }]
    }
    dd = {}
    dd['bb'] = all_dic
    return JsonResponse(treeviewInfo)


@csrf_exempt
def getPortParameter(request):
    '''
    get port ajax post parameter: client parameter
    '''
    data = request.POST

    pass


# test view function :

def pinInfop(request):
    '''
    treeview本身是个特殊的类型[{'text':'sss'},{'text':'bbb'}]
    数组嵌套字典，且所有元素的字典的key值均为text。
    '''
    # 存储所有接口名
    payuiName = []
    each_dic = []
    bb = {}
    # 拼接[{text:'xx'}]模式的是treeview
    all_dic = []
    payuiinfo = PortInfo.objects.filter(portsystem='phptradeui')
    for i in payuiinfo:
        # print i.portname
        payuiName.append(i.portname)
        each_dic.append(i.portname)
    for i in range(len(payuiName)):
        each_dic[i] = {'text': ''}
        all_dic.append(each_dic[i])
    for num_time in range(len(payuiName)):
        all_dic[num_time]['text'] = payuiName[num_time]

    print 'alldic', all_dic
    treeviewInfo = {
        'text': "jdb",  # 节点显示的文本值  string
        'selectable': True,  # 标记节点是否可以选择。false表示节点应该作为扩展标题，不会触发选择事件。  string
        'state': {  # 描述节点的初始状态    Object
            'checked': True,  # 是否选中节点
        },
        'tags': ['标签信息1', '标签信息2'],  # //向节点的右侧添加附加信息（类似与boostrap的徽章）    Array of Strings
        'nodes': [{
            'text': "Child 1",

            'nodes': all_dic
        }, {
            'text': "Child 2"
        }]
    }

    return HttpResponse('sssss')
